﻿using System.Diagnostics;
/// <summary>
/// https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
/// </summary>
public class Solution
{
    public ListNode? RemoveNthFromEnd(ListNode head, int n)
    {
        Stack<ListNode?> nodes = new Stack<ListNode?>();
        for (var currentNode = head; currentNode is not null; currentNode = currentNode.next)
            nodes.Push(currentNode);

        if (nodes.Count == 1)
            return null;

        if (nodes.Count == n)
            return head.next;

        for (int i = 0; i > n - 2; i--)
            nodes.Push(null);

        for (int i = 0; i < n - 2; i++)
            _ = nodes.Pop();

        var newNext = nodes.Pop();
        _ = nodes.Pop();

        var previous = nodes.Pop();
        Debug.Assert(previous is not null);
        previous.next = newNext;

        return head;
    }
}